Spread Operator - 人員資訊範例

範例說明:

此範例展示了如何結合使用 Rest Parameters 和 Spread Operator:

function showPerson(firstname, lastname, ...titles) {
  let sentence = firstname + " " + lastname + " is ";

  for (let i = 0; i < titles.length; i++) {
    if (i !== titles.length - 1) {
      sentence += "a " + titles[i] + ", ";
    } else {
      if (titles.length === 1) {
        sentence += "a " + titles[i];
      } else {
        sentence += "and a " + titles[i];
      }
    }
  }

  console.log(sentence);
}

// ✅ 改成使用 Spread 呼叫
const person1 = ["Keith", "Fung", "Firefighter"];
const person2 = ["Marvin", "Chan", "Highschool student", "Pet Owner"];
const person3 = ["Justin", "Lau", "Consultant", "Hiker", "Camper"];
const person4 = ["Justin", "Lau", "Consultant", "Hiker", "Camper", "Blogger", "Foodie"];

showPerson(...person1);
showPerson(...person2);
showPerson(...person3);
showPerson(...person4);

範例解析:

Spread Operator ... 將陣列元素展開,相當於:

執行結果: